package com.android.manghe.orderpay.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.DisplayUtil
import com.android.base.tools.Glide.GlideHelper
import com.android.base.tools.ToastUtil
import com.android.base.view.recycler.RecyclerViewDivider
import com.android.manghe.R
import com.android.manghe.common.activity.PayFailActivity
import com.android.manghe.common.activity.PaySuccessActivity
import com.android.manghe.common.model.BuyGoodShangMengZhiFuRes
import com.android.manghe.common.model.PaymentTypeRes
import com.android.manghe.common.webview.SimpleWebViewActivity
import com.android.manghe.config.events.PaySuccessEvent
import com.android.manghe.config.events.RefreshCartEvent
import com.android.manghe.config.events.RefreshMemberInfoEvent
import com.android.manghe.coupon.adapter.PaymentAdapter
import com.android.manghe.mine.activity.AddressListActivity
import com.android.manghe.mine.model.AddressInfo
import com.android.manghe.orderpay.model.MarketOrderInfoRes
import com.android.manghe.orderpay.presenter.PMarketOrder
import com.android.manghe.quickpay.activity.QuickPayDetailActivity
import com.android.manghe.view.AutoHeightLayoutManager
import com.android.manghe.view.dialog.ConfirmPayResultDialog
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import kotlinx.android.synthetic.main.activity_order_pay.*
import java.text.DecimalFormat

/**
 * 确认订单界面，  底部有结算按钮，直接结算
 */
class MarketOrderPayActivity : MVPActivity<PMarketOrder>() {

    private val ReqCode_SelectAddress = 1001
    private var mPaymentAdapter :PaymentAdapter? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_order_pay
    }

    override fun initData(savedInstanceState: Bundle?) {
        Bus.observe<PaySuccessEvent>().subscribe {
            Bus.send(RefreshCartEvent())
            finish()
        }.registerInBus(this)

        p.goodId = intent.getStringExtra("goodId")
        p.spec = intent.getStringExtra("spec")
        p.qty = intent.getIntExtra("qty", 1)

        titleBar.setToolbar("确认订单").setLeftIcon(R.mipmap.icon_back_black).setTitleAndStatusBgColor(R.color.white)
//        val config = ConfigHolder.getConfigInfo(this)
//        if (config != null && config.order_exempt_rule_switch == 1) {
//            titleBar.setRightText("规则") {
//                AnalyzeUtil.clickRule(this, 2)
//                WebTextActivity.showActivity(
//                    this,
//                    "商品助力规则",
//                    ConstantsUrl.domain + ConstantsUrl.ZHULI_RULE
//                )
//            }.setRightFontColor(ContextCompat.getColor(this, R.color.colorFont99))
//        }

        paymentRecyclerView.layoutManager = AutoHeightLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mPaymentAdapter = PaymentAdapter(this, ArrayList<PaymentTypeRes.DataBean.PaymentBean>())
        mPaymentAdapter!!.hideDesc()
        paymentRecyclerView.addItemDecoration(RecyclerViewDivider(this, LinearLayoutManager.HORIZONTAL))
        paymentRecyclerView.adapter = mPaymentAdapter

        p.loadOrderInfo(false, null)
        p.loadAddressList()
        p.getPaymentType()
        tvTotalQtyTip.text = "共${p.qty}件商品"

        layoutAddress.setOnClickListener {
            //添加地址,切换地址
            open(AddressListActivity::class.java, hashMapOf<String, Any>("isToSelect" to true),ReqCode_SelectAddress)
        }
        mPaymentAdapter?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.data[position] as PaymentTypeRes.DataBean.PaymentBean
            mPaymentAdapter?.selectedItem(item)
            p.setPayType(item)
        }
        tvPay.setOnClickListener {
            layoutPay.visibility = View.VISIBLE
        }
        btnConfirmPay.setOnClickListener {
            if(p.currentAddress == null){
                ToastUtil.showShort(this@MarketOrderPayActivity, "请填写配送地址")
            }else if(p.orderInfo != null){
                layoutPay.visibility = View.GONE
                p.loadOrderInfo(true, etMark.text.toString().trim())
            }
        }
        ivClosePay.setOnClickListener {
            layoutPay.visibility = View.GONE
        }
        layoutPay.setOnClickListener {
            layoutPay.visibility = View.GONE
        }
    }

    override fun onBackPressed() {
        if(layoutPay.visibility == View.VISIBLE){
            layoutPay.visibility = View.GONE
        }else {
            super.onBackPressed()
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode == Activity.RESULT_OK){
            if(ReqCode_SelectAddress == requestCode){
                p.setCurrentAddress(data?.getSerializableExtra("addressInfo") as AddressInfo)
                showAddress(p.currentAddress)
            }else if(requestCode == 1000 || requestCode == 2000){
                if(data != null  && data.extras != null && data.extras.getBoolean("fail" , false)){
                    finish()
                    open(PayFailActivity::class.java)
                    Bus.send(RefreshMemberInfoEvent())
                    return
                }
                //翼支付、快捷支付 支付成功
                finish()
                open(PaySuccessActivity::class.java)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }

    fun showGoodDetail(detail: MarketOrderInfoRes.DataBean?){
        try{
            if(detail!=null) {
                var goodInfo : MarketOrderInfoRes.DataBean.CartGoodsBean? = null
                for(bean  in  detail.cart_goods){
                    if(bean.goods_id == p.goodId){
                        goodInfo = bean
                        break
                    }
                }
                if(goodInfo == null){
                    ToastUtil.showLong(this, "获取订单信息失败")
                    finish()
                    return
                }
                GlideHelper.loadWithHolderErr(this, goodInfo.img_src, ivGoodPic)
                tvGoodTitle.text = goodInfo.goods_name
                tvSpecName.text = "${goodInfo.goods_spec}"
                tvQyt.text = "x${p.qty}"

                var price = detail.total.goods_amount.toDouble()
                val format = DecimalFormat("0.00")
                val priceStr = format.format(price)
                tvTruePrice.text = "￥$priceStr"
                tvPriceSmall.text = tvTruePrice.text
                return
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
        ToastUtil.showShort(this, "获取订单信息出错")
    }

    fun showAddress(addressInfo: AddressInfo?){
        p.setCurrentAddress(addressInfo)
        if(addressInfo == null){
            layoutAddAddress.visibility = View.VISIBLE
            layoutHaveAddress.visibility = View.GONE
        }else{
            layoutAddAddress.visibility = View.GONE
            layoutHaveAddress.visibility = View.VISIBLE

            tvAddrName.text = addressInfo.name
            tvAddrTel.text = addressInfo.mobile
            tvAddr.text = addressInfo.area +" "+ addressInfo.address
        }
    }
    fun updatePayments(paymentList : List<PaymentTypeRes.DataBean.PaymentBean>){

        mPaymentAdapter?.let {
            it.update(paymentList)
        }
        try{
            val lp = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,paymentList.size * DisplayUtil.dip2px(this, 60f))
            lp.topMargin = DisplayUtil.dip2px(this, 20f)
            lp.bottomMargin = DisplayUtil.dip2px(this, 20f)
            paymentRecyclerView.layoutParams = lp
        }catch (e:java.lang.Exception){
            e.printStackTrace()
        }
    }



    fun payFail(){
        ToastUtil.showShort(this, "未完成支付")
    }

    fun paySuccess(){
        finish()
        open(PaySuccessActivity::class.java)
    }

    fun toPayByH5(url: String) {
        SimpleWebViewActivity.showActivity(this, url, "支付")
    }

    fun openQuickPay(buyGoodShangMengZhiFuData: BuyGoodShangMengZhiFuRes.DataBean){
        open(QuickPayDetailActivity::class.java, mapOf("buyGoodShangMengZhiFuData" to buyGoodShangMengZhiFuData), 2000)
    }

    fun toPayByBrowser(url: String, orderId: String) {
        val uri: Uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
        //弹出让用户确定是否支付成功的弹出框
        orderId?.let {
            val dialog = ConfirmPayResultDialog(this, orderId, object : ConfirmPayResultDialog.CallBack{
                override fun callBack(orderId: String) {
                    //显示支付成功界面
                    p.checkOrderStatus(orderId)
                }
            })
            dialog.show()
        }
    }
}